<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-form-item label="关联客户" prop="customerId">
        <customer-select
          v-model="formData.customerId"
          :disabled="isFromCustomerDetail"
          @change="handleCustomerChange"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactId">
        <contact-person-select
          v-model="formData.contactId"
          :customer-id="formData.customerId"
          @change="handleContactChange"
        />
      </el-form-item>
      <el-form-item label="机会标题" prop="opportunityTitle">
        <el-input v-model="formData.opportunityTitle" placeholder="请输入机会标题" />
      </el-form-item>
      
      <el-form-item label="预订金额" prop="estimatedAmount">
        <el-input-number v-model="formData.estimatedAmount" :min="0" :precision="2" :step="1000" />
      </el-form-item>
      <el-form-item label="发现时间" prop="discoveryTime">
        <el-date-picker
          v-model="formData.discoveryTime"
          type="datetime"
          placeholder="请选择发现时间"
          value-format="x"
        />
      </el-form-item>
      <el-form-item label="预订签单时间" prop="estimatedSignTime">
        <el-date-picker
          v-model="formData.estimatedSignTime"
          type="datetime"
          placeholder="请选择预订签单时间"
          value-format="x"
        />
      </el-form-item>
      <el-form-item label="归属人员" prop="ownerId">
        <user-select
          v-model="formData.ownerId"
          @node-change="handleOwnerChange"
        />
      </el-form-item>
      <el-form-item label="协助人员" prop="assistantId">
        <user-select-multiple
          v-model="formData.assistantId"
          @node-change="handleAssistantChange"
        />
      </el-form-item>
      <el-form-item label="需求描述" prop="demandDescription">
        <el-input
          v-model="formData.demandDescription"
          type="textarea"
          placeholder="请输入需求描述"
          :rows="4"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { SalesLeadApi, SalesLeadVO } from '@/api/oa/saleslead'
import CustomerSelect from '../customer/components/CustomerSelect.vue'
import ContactPersonSelect from '../customer/components/ContactPersonSelect.vue'
import UserSelect from '@/views/system/user/UserSelect.vue'
import UserSelectMultiple from '@/views/system/user/UserSelectMultiple.vue'

/** 销售线索 表单 */
defineOptions({ name: 'SalesLeadForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formRef = ref() // 表单 Ref
const isFromCustomerDetail = ref(false) // 是否从客户详情页面打开

const formData = ref<SalesLeadVO>({
  id: undefined,
  customerId: undefined,
  contactId: undefined,
  opportunityTitle: undefined,
  demandDescription: undefined,
  estimatedAmount: undefined,
  discoveryTime: undefined,
  estimatedSignTime: undefined,
  ownerId: undefined,
  assistantIds: undefined,
  creatorName: undefined,
  updaterName: undefined
})

const formRules = reactive({
  customerId: [{ required: true, message: '关联客户不能为空', trigger: 'change' }],
  contactId: [{ required: true, message: '联系人不能为空', trigger: 'change' }],
  opportunityTitle: [{ required: true, message: '机会标题不能为空', trigger: 'blur' }],
  demandDescription: [{ required: true, message: '需求描述不能为空', trigger: 'blur' }],
  estimatedAmount: [{ required: true, message: '预订金额不能为空', trigger: 'change' }],
  discoveryTime: [{ required: true, message: '发现时间不能为空', trigger: 'change' }],
  estimatedSignTime: [{ required: true, message: '预订签单时间不能为空', trigger: 'change' }],
  ownerId: [{ required: true, message: '归属人员不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number, customerInfo?: { customerId: number; customerName: string }) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  // 重置表单
  formRef.value?.resetFields()
  // 重置表单数据
  formData.value = {
    id: undefined,
    customerId: undefined,
    contactId: undefined,
    opportunityTitle: undefined,
    demandDescription: undefined,
    estimatedAmount: undefined,
    discoveryTime: undefined,
    estimatedSignTime: undefined,
    ownerId: undefined,
    assistantId: undefined,
    creatorName: undefined,
    updaterName: undefined
  }
  // 设置是否从客户详情页面打开
  isFromCustomerDetail.value = !!customerInfo
  if (customerInfo) {
    formData.value.customerId = customerInfo.customerId
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await SalesLeadApi.getSalesLead(id)
      // 处理协助人员ID，将字符串转换为数组
      if (data.assistantIds) {
        data.assistantIds = data.assistantIds.split(',').map(Number)
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value }
    // 处理协助人员ID，确保是字符串格式
    if (Array.isArray(data.assistantId)) {
      data.assistantId = data.assistantId.join(',')
    }
    if (data.id) {
      await SalesLeadApi.updateSalesLead(data)
      message.success(t('common.updateSuccess'))
    } else {
      await SalesLeadApi.createSalesLead(data)
      message.success(t('common.createSuccess'))
    }
    dialogVisible.value = false
    // 通知操作成功
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 处理客户选择变化 */
const handleCustomerChange = (customer: any) => {
  if (customer) {
    // 清空联系人信息
    formData.value.contactId = undefined
  } else {
    formData.value.contactId = undefined
  }
}

/** 处理联系人选择变化 */
const handleContactChange = (contact: any) => {
  if (contact) {
    formData.value.contactId = contact.id
  } else {
    formData.value.contactId = undefined
  }
}

/** 处理归属人员选择变化 */
const handleOwnerChange = (user: any) => {
  if (user) {
    formData.value.ownerId = user.id
    formData.value.ownerName = user.nickname // 同时保存用户名称
  } else {
    formData.value.ownerId = undefined
    formData.value.ownerName = undefined
  }
}

/** 处理协助人员选择变化 */
const handleAssistantChange = (users: any[]) => {
  if (users && users.length > 0) {
    formData.value.assistantId = users.map(user => user.id)
    formData.value.assistantNames = users.map(user => user.nickname).join(',')
  } else {
    formData.value.assistantId = undefined
    formData.value.assistantNames = undefined
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>